<template>
  <el-main>
    <div class="margin-bottom-20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/user' }"
          >用户管理</el-breadcrumb-item
        >
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="clearfix">
      <el-form class="pull-left" inline>
        <el-form-item>
          <el-input
            placeholder="请输入账号"
            v-model="search_param.accountName"
          />
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入手机号" v-model="search_param.mobile" />
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入邮箱" v-model="search_param.email" />
        </el-form-item>
        <el-form-item>
          <el-select
            placeholder="请选择所属企业"
            v-model="search_param.companyId"
          >
            <el-option
              :key="item.id"
              :label="item.companyName"
              :value="item.id"
              v-for="item in companyList"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button-group>
            <el-button
              @click="handleSearch"
              icon="el-icon-search"
              size="medium"
              type="primary"
              >搜索
            </el-button>
            <el-button @click="handleReset" size="medium" type="primary"
              >重置
            </el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
      <el-form class="pull-right" inline>
        <el-form-item>
          <el-button-group>
            <el-button @click="handleAdd" size="medium" type="primary"
              >新增用户
            </el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="box-card" shadow="never">
      <el-table :data="table_data" stripe style="width: 100%">
        <el-table-column
          label="账号"
          prop="accountName"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column label="注册时间" prop="ctime" width="160" />
        <el-table-column label="手机号" prop="mobile" show-overflow-tooltip />
        <el-table-column label="邮箱" prop="email" show-overflow-tooltip />
        <el-table-column label="地址" prop="address" show-overflow-tooltip />
        <el-table-column
          label="隶属公司"
          prop="companyName"
          show-overflow-tooltip
        />
        <el-table-column label="简介" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" size="mini" type="text"
              >修改
            </el-button>
            <el-button @click="handlePasswd(scope.row)" size="mini" type="text"
              >重置密码
            </el-button>
            <el-button @click="handleDelete(scope.row)" size="mini" type="text"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="margin-top-10 clearfix">
        <el-pagination
          :current-page.sync="current_page"
          :page-size.sync="page_size"
          :page-sizes="[5, 10, 20]"
          :total="total_size"
          @current-change="load_table_data"
          @size-change="load_table_data"
          background
          class="pull-right"
          layout="total, sizes,  prev, pager, next"
        />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="passwdDialogVisible"
      @close="dialogClose"
      title="重置密码"
      width="50%"
    >
      <el-form
        :model="passwdForm"
        :rules="passwdRules"
        label-width="100px"
        ref="passwdForm"
        style="max-width: 400px"
      >
        <el-form-item label="账号">
          {{ passwdForm.accountName }}
        </el-form-item>
        <el-form-item label="新密码" prop="newPasswd">
          <el-input
            autocomplete="off"
            show-password
            type="password"
            v-model="passwdForm.newPasswd"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="rePasswd">
          <el-input
            autocomplete="off"
            show-password
            type="password"
            v-model="passwdForm.rePasswd"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handlePasswdSubmit('passwdForm')" type="primary"
          >确 定
        </el-button>
        <el-button @click="passwdDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-main>
</template>

<script>
import { mapActions, mapState } from "vuex";

export default {
  data() {
    const validateRePasswd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwdForm.newPasswd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      passwdDialogVisible: false,
      passwdForm: {
        id: null,
        accountName: null,
        newPasswd: null,
        rePasswd: null
      },
      passwdRules: {
        newPasswd: [
          { required: true, message: "请输入密码", trigger: "none" },
          { min: 3, max: 25, message: "长度在 3 到 25 个字符", trigger: "none" }
        ],
        rePasswd: [
          { required: true, message: "请再次输入密码", trigger: "none" },
          { validator: validateRePasswd, trigger: "none" }
        ]
      },
      companyList: []
    };
  },
  mounted() {
    this.load_table_data();
    this.companyOptions();
  },
  computed: {
    ...mapState("user", ["total_size", "table_data"]),
    page_size: {
      get() {
        return this.$store.state.user.page_size;
      },
      set(value) {
        this.set_page_size(value);
      }
    },
    current_page: {
      get() {
        return this.$store.state.user.current_page;
      },
      set(value) {
        this.set_current_page(value);
      }
    },
    search_param: {
      get() {
        return this.$store.state.user.search_param;
      }
    }
  },
  methods: {
    ...mapActions("user", [
      "load_table_data",
      "set_page_size",
      "set_current_page",
      "set_search_param"
    ]),
    handleSearch() {
      this.set_search_param(Object.assign({}, this.search_param));
      this.load_table_data();
    },
    handleReset() {
      this.set_search_param({});
      this.load_table_data();
    },
    handleAdd() {
      this.$router.push("/user/system/add");
    },
    handleEdit(row) {
      this.$router.push("/user/system/edit/" + row.id);
    },
    handlePasswd(row) {
      this.passwdForm.id = row.id;
      this.passwdForm.accountName = row.accountName;
      this.passwdForm.realName = row.realName;
      this.passwdDialogVisible = true;
    },
    dialogClose() {
      this.$refs["passwdForm"].resetFields();
    },
    handlePasswdSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let loadingInstance = this.$loading({ fullscreen: true });
          this.$ajax.user
            .repasswd(this.passwdForm.id, { passwd: this.passwdForm.newPasswd })
            .then(result => {
              if (result.code != 1) {
                this.$message({
                  message: result.msg,
                  type: "warning"
                });
              } else {
                this.$message({
                  type: "success",
                  message: "重置密码成功!"
                });
                this.passwdDialogVisible = false;
              }
            })
            .catch(e => {
              console.log(e);
              this.$message({
                message: "系统繁忙，请稍后重试",
                type: "warning"
              });
            })
            .finally(function() {
              loadingInstance.close();
            });
        } else {
          return false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        "此操作将永久删除用户：" + row.accountName + " , 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        let loadingInstance = this.$loading({ fullscreen: true });

        this.$ajax.user
          .remove(row.id)
          .then(result => {
            if (result.code != 1) {
              this.$message({
                message: result.msg,
                type: "warning"
              });
            } else {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.load_table_data();
            }
          })
          .catch(e => {
            console.log(e);
            this.$message({
              message: "系统繁忙，请稍后重试",
              type: "warning"
            });
          })
          .finally(function() {
            loadingInstance.close();
          });
      });
    },
    companyOptions() {
      this.$ajax.company
        .options()
        .then(result => {
          if (result.code == 1) {
            this.companyList = result.data;
          } else {
            this.$message({
              message: result.msg,
              type: "warning"
            });
          }
        })
        .catch(e => {
          console.log(e);
          this.$message({
            message: "系统繁忙，请稍后重试",
            type: "warning"
          });
        });
    }
  }
};
</script>
